import axios, { type Method } from "axios";
import { getLocalToken } from "./auth";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import router from "@/router";

const service = axios.create({
  baseURL: "https://api-hmzs.itheima.net/tj",
  timeout: 5000,
});

service.interceptors.request.use(
  (config) => {
    const token = getLocalToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    ElMessage.error(error.response.data.msg);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // 处理token失效
    if (error.response.status === 401) {
      ElMessage.error("登录已过期，请重新登录");
      // 清空token
      const store = useUserStore();
      store.setToken("");
      // 拦截跳转登录
      router.replace("/login");
    } else {
      ElMessage.error(error.response.data.msg);
    }

    return Promise.reject(error);
  }
);

type Data<T> = {
  code: number;
  message: string;
  data: T;
};

// 封装request方法
const request = <T>(url: string, method: Method = "GET", data?: object) => {
  return service.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === "get" ? "params" : "data"]: data,
  });
};

// 导出
export { request, service };
